import axios from 'axios';
import store from '@/store';
import NProgress from 'nprogress'; // nprogress插件
import utils from '@common/utils/utils';
import { Loading } from 'element-ui';
import constants from "@common/api/constants";

let loading = undefined;
const showLoading = (text) => {
	if (!text) {
		text = '加载中...';
	}
	loading = Loading.service({
		lock: true,
		text,
		spinner: 'el-icon-loading',
		background: 'rgba(0, 0, 0, 0.5)',
		customClass: 'tsd_loading',
	});
};
const closeLoading = () => {
	if (loading) {
		loading.close();
	}
};
const service = axios.create({
	baseURL: window.configs.requestPrefix,
	method: 'post',
	timeout: window.configs.REQUEST_TIMEOUT,
	withCredentials: true,
});
service.interceptors.request.use(
	config => {
		config.loading = false;
		let formHideLoading = false;
		if (config.data && config.data.get) {
			formHideLoading = "true" === config.data.get("hideLoading");
		}
		if (config.data.hideLoading !== true && !formHideLoading) {
			config.hideLoading = config.data.hideLoading;
			NProgress.start();
		}
		let contentType = config.headers['Content-Type'];
		if (!utils.isNotEmpty(contentType)) {
			config.headers['Content-Type'] = 'application/json;charset=UTF-8';
		}
		config.headers['Access-Control-Allow-Origin'] = '*';
		config.headers['Access-Control-Allow-Methods'] = '*';
        if (utils.isEmpty(config.headers['token'])) {
            let accessToken = store.state.accessToken;
            if (accessToken) {
                config.headers['token'] = accessToken.token;
            }
        }
        if (utils.isNotEmpty(store.state.application)) {
            config.headers['application'] = store.state.application;
        }
		config.headers['account_set_sid'] = utils.getAccountSetSid();
        if (config.url.indexOf(constants.API_GetVerifyCode) !== -1) {
            delete config.headers['account_set_sid'];
        }
        if (utils.isEmpty(config.headers['refresh_token'])) {
            let refreshToken = store.state.refreshToken;
            if (refreshToken) {
                config.headers['refresh_token'] = refreshToken.token;
            }
        }
		config.headers["tmn"] = utils.getBrowserType();
		if (config.data) {
			if (contentType === 'multipart/form-data') {
				config.data.append("dr", 0);
				let load = config.data.get('loading');
				if (load && load === 'true') {
					config.loading = true;
					showLoading(config.data.get('loadingText'));
					config.data.delete('loading');
					if (config.data.get('loadingText')) {
						config.data.delete('loadingText');
					}
				}
				if (typeof config.data.get('hideLoading') !== undefined) {
					config.data.delete('hideLoading');
				}
			} else {
				if (config.data.loading) {
					config.loading = true;
					showLoading(config.data.loadingText);
					delete config.data.loading;
					if (config.data.loadingText) {
						delete config.data.loadingText;
					}
				}
				if (typeof config.data.hideLoading !== undefined) {
					delete config.data.hideLoading;
				}
				if (!config.data.dr) {
					config.data.dr = 0;
				}
				config.data = JSON.stringify(config.data);
			}
		}
		return config;
	},
	error => {
		let config = error.config;
		if (config.hideLoading !== true) {
			NProgress.done();
		}
		return Promise.reject(error);
	}
);
service.interceptors.response.use(
	response => {
		let config = response.config;
		if (config.loading) {
			closeLoading();
		}
		if (config.hideLoading !== true) {
			NProgress.done();
		}
		if (utils.isNotEmpty(response.headers['verifysession'])) {
			utils.setSessionStorage('VerifySession', response.headers['verifysession']);
		}
		let refresh = false;
		let userInfo = $.extend({}, store.state.userInfo);
		if (utils.isNotEmpty(response.headers['token'])) {
			let accessToken = store.state.accessToken;
			accessToken = $.extend({}, accessToken, {
				token: response.headers['token'],
			});
			userInfo = $.extend({}, userInfo, { accessToken });
			refresh = true;
		}
		if (utils.isNotEmpty(response.headers['refresh_token'])) {
			let refreshToken = store.state.refreshToken;
			refreshToken = $.extend({}, refreshToken, {
				token: response.headers['refresh_token'],
			});
			userInfo = $.extend({}, userInfo, { refreshToken });
			refresh = true;
		}
		if (refresh) {
			store.commit('setUserInfo', userInfo);
		}
		return Promise.resolve(response.data);
	},
	error => {
		let config = error.config;
        if (config) {
            if (config.loading) {
                closeLoading();
            }
            if (config.hideLoading !== true) {
                NProgress.done();
            }
        }
		if (error && error.response) {
			switch (error.response.status) {
				case 400:
					error.response.statusText = '错误请求';
					break;
				case 401:
					error.response.statusText = '未授权，请重新登录';
					break;
				case 403:
					error.response.statusText = '拒绝访问';
					break;
				case 404:
					error.response.statusText = '请求错误，未找到该资源';
					break;
				case 405:
					error.response.statusText = '请求方法不允许';
					break;
				case 408:
					error.response.statusText = '请求超时';
					break;
				case 500:
					error.response.statusText = '服务器端出错';
					break;
				case 501:
					error.response.statusText = '网络未实现';
					break;
				case 502:
					error.response.statusText = '网络错误';
					break;
				case 503:
					error.response.statusText = '服务不可用';
					break;
				case 504:
					error.response.statusText = '网络超时';
					break;
				case 505:
					error.response.statusText = 'http版本不支持该请求';
					break;
				default:
					error.response.statusText = `错误代码：${ error.response.status }`;
					break;
			}
		}
		let errRes = {};
		errRes.code = -999;
		if (error.response) {
			if (error.response.data) {
				errRes.data = error.response.data;
			}
			errRes.message = error.response.status + " " + error.response.statusText;
		} else {
			errRes.message = error.message;
		}
		return Promise.reject(errRes);
	}
);
export default service;
